package jwei.apps.indextank.db;

import jwei.apps.indextank.db.IngredientCache.IngredientsCache;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class IngredientDb {

    private IngredientDb() {
    }

    private static final IngredientDb instance = new IngredientDb();

    public static IngredientDb getInstance() {
        return instance;
    }

    public void addIngredient(ContentResolver contentResolver, String ingredient) {
        if (!isCached(contentResolver, ingredient)) {
            ContentValues contentValue = new ContentValues();
            contentValue.put(IngredientsCache.NAME, ingredient);
            contentResolver.insert(IngredientsCache.CONTENT_URI, contentValue);
        }
    }

    public void removeIngredient(ContentResolver contentResolver, int id) {
        Uri s = ContentUris.withAppendedId(IngredientsCache.CONTENT_URI, id);
        contentResolver.delete(s, null, null);
    }

    public boolean isCached(ContentResolver contentResolver, String ingredient) {
        boolean ret = false;
        Cursor c = contentResolver.query(IngredientsCache.CONTENT_URI, new String[] { IngredientsCache._ID },
                IngredientsCache.NAME + "='" + ingredient + "'", null, null);
        if (c == null) { return false; }
        if (c.moveToNext()) {
            ret = true;
        }
        c.close();
        return ret;
    }

    public boolean isEmpty(ContentResolver contentResolver) {
        boolean ret = true;
        String[] projection = new String[] { IngredientsCache._ID };
        Cursor c = contentResolver.query(IngredientsCache.CONTENT_URI, projection, null, null, null);
        if (c == null) { return false; }
        if (c.moveToNext()) {
            ret = false;
        }
        c.close();
        return ret;
    }

    // delete all ingredients
    public void refreshCache(ContentResolver contentResolver) {
        contentResolver.delete(IngredientsCache.CONTENT_URI, "1", null);
    }

}
